package com.gx.util.base;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author gaoxing
 * @create 2018-06-19 下午3:55
 */
@Slf4j
public class BaseProcessUtils {

    public static String run(String... commands) {
        ProcessBuilder processBuilder = new ProcessBuilder(commands);

        Process process;
        try {
            process = processBuilder.redirectErrorStream(true).start();
        } catch (Exception var12) {
            throw new RuntimeException("启动进程" + Arrays.asList(commands) + "异常", var12);
        }

        StringBuilder buf = new StringBuilder();

        try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));) {
            String line;
            while ((line = in.readLine()) != null) {
                buf.append(line);
            }
        } catch (Exception var13) {
            throw new RuntimeException("从process中读取数据异常", var13);
        }
        int errorCode;
        try {
            errorCode = process.waitFor();
        } catch (Throwable var11) {
            log.error("获取进程结果异常");
            throw new RuntimeException(var11);
        }

        if (errorCode == 0) {
            return buf.toString();
        } else {
            throw new RuntimeException(String.format("process执行异常.错误码[%s],异常信息:%s", errorCode, buf.toString()));
        }
    }

}
